package com.ttmusic.dao;

import java.util.List;

import com.ttmusic.entity.ArtistInfo;
import com.ttmusic.utils.MusicUtils;
import com.ttmusic.utils.SQLite.SQLiteUtil;

import android.database.Cursor;

/**
 * 歌手信息dao
 * @author Administrator
 *
 */
public class ArtistInfoDao implements BaseDao<ArtistInfo>{
	
	//单例模式
	private ArtistInfoDao() {}
	private static ArtistInfoDao artistDao = new ArtistInfoDao();
	public static ArtistInfoDao getInstance() {
		return artistDao;
	}

	/**
	 * 查找所有歌手信息
	 */
	@Override
	public List<ArtistInfo> findAll() {
		String sql = "select ARTIST_ID,ARTIST,NUM_SONGS,ALBUM_ART from TB_ARTIST_INFO ORDER BY ARTIST_ID ASC";
		Cursor cursor = SQLiteUtil.executeQuery(sql);
		return MusicUtils.getArtistList(cursor);
	}

	/**
	 * 通过主键id查找一个歌手信息
	 */
	@Override
	public ArtistInfo loadById(Long id) {
		String sql = "select ARTIST_ID,ARTIST,NUM_SONGS,ALBUM_ART from TB_ARTIST_INFO where ARTIST_ID=?";
		Cursor cursor = SQLiteUtil.executeQuery(sql, id.toString());
		List<ArtistInfo> list = MusicUtils.getArtistList(cursor);
		if(null != list && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
	
	/**
	 * 通过名称查找一个歌手信息
	 */
	@Override
	public ArtistInfo loadByName(String name) {
		String sql = "select ARTIST_ID,ARTIST,NUM_SONGS,ALBUM_ART from TB_ARTIST_INFO where ARTIST=?";
		Cursor cursor = SQLiteUtil.executeQuery(sql, name);
		List<ArtistInfo> list = MusicUtils.getArtistList(cursor);
		if(null != list && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	/**
	 * 保存歌手信息到自己创建的TB_ARTIST_INFO表中
	 * @param artist
	 */
	@Override
	public long save(ArtistInfo artist) {
		//插入数据时不填主键  自动递增
		String sql = "insert into TB_ARTIST_INFO(ARTIST,NUM_SONGS,ALBUM_ART) values(?,?,?)";
		SQLiteUtil.executeDML(sql, artist.getArtist(), artist.getNumSongs(), artist.getAlbumArt());
		
		//查找当前插入的数据主键值
		sql = "select MAX(ARTIST_ID) as MAX_ARTIST_ID from TB_ARTIST_INFO";
		Cursor c = SQLiteUtil.executeQuery(sql);
		if(c.getCount() > 0 && c.getColumnCount() > 0) {
			c.moveToNext();
			return c.getLong(c.getColumnIndex("MAX_ARTIST_ID"));
		}
		return -1;
	}

	/**
	 * 修改歌手信息
	 */
	@Override
	public void update(ArtistInfo artist) {
		String sql = "update TB_ARTIST_INFO set ARTIST=?,NUM_SONGS=?,ALBUM_ART=? where ARTIST_ID=?";
		SQLiteUtil.executeDML(sql, artist.getArtist(), artist.getNumSongs(), artist.getAlbumArt(), artist.getArtistId());
	}
	

	/**
	 * 删除歌手信息
	 */
	@Override
	public void delete(Long id) {
		String sql = "delete from TB_ARTIST_INFO where ARTIST_ID=?";
		SQLiteUtil.executeDML(sql, id);
	}

}
